package gozerocommon

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/metadata"
)

type CtxKey string

var ClientIP = CtxKey("client_ip")

var CtxKeyJwtUserId = "jwtUserId"
var CtxKeyJwtEntityId = "entityId"

func GetClientIPFromCtx(ctx context.Context) string {
	if ip, ok := ctx.Value(ClientIP).(string); ok {
		return ip
	}
	return ""
}

func GetClientIPFromMetadata(ctx context.Context) string {

	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return ""
	}
	clientIp := ""
	if ip, ok := md["client_ip"]; ok {
		fmt.Println(ip)
		clientIp = ip[0]
	}
	return clientIp
}

func GetUidFromCtx(ctx context.Context) int64 {
	var uid int64
	if jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(json.Number); ok {
		if int64Uid, err := jsonUid.Int64(); err == nil {
			uid = int64Uid
		} else {
			logx.WithContext(ctx).Error("GetUidFromCtx err :%+v", err)
		}
	}
	return uid
}

func GetUserIdAndEntityIdFromCtx(ctx context.Context) (int64, string) {
	var uid int64
	var entityId string
	if jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(json.Number); ok {
		if int64Uid, err := jsonUid.Int64(); err == nil {
			uid = int64Uid
		} else {
			logx.WithContext(ctx).Error("GetUidFromCtx err :%+v", err)
		}
	}
	if jsonEntityId, ok := ctx.Value(CtxKeyJwtEntityId).(string); ok {
		entityId = jsonEntityId
	}
	return uid, entityId
}

func GetUidStringFromCtx(ctx context.Context) string {
	var uid string
	if jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(string); ok {
		if jsonUid != "" {
			uid = jsonUid
		} else {
			logx.WithContext(ctx).Error("GetUidFromCtx err")
		}
	}
	return uid
}
